#define _POSIX_C_SOURCE 200809L
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *shards[] = {"app-frontend", "app-backend", "db-proxy"};
    int n = (int)(sizeof(shards) / sizeof(shards[0]));

    for (int i = 0; i < n; ++i) {
        pid_t pid = fork();
        if (pid < 0) {
            return 1;
        }
        if (pid == 0) {
            // 统一使用项目根目录的 logs 绝对路径
            char project_root[1024];
            if (getcwd(project_root, sizeof(project_root)) == NULL) _exit(1);
            char log_path[1200];
            snprintf(log_path, sizeof(log_path), "%s/logs/archive.log", project_root);

            // 放大缓冲区并做截断检查
            char cmd[2048];
            int used = snprintf(cmd, sizeof(cmd),
                                "sleep 1; echo \"$(date '+%%F %%T') [archive] shard %s done by pid %d\" >> '%s'",
                                shards[i], getpid(), log_path);
            if (used < 0 || used >= (int)sizeof(cmd)) _exit(1);
            execlp("sh", "sh", "-c", cmd, (char *)NULL);
            _exit(127);
        }
    }

    sleep(20);
    return 0;
}